package com.pf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pf.dto.ResultResp;
import com.pf.dto.UploadFileResp;
import com.pf.helper.CustomFileHelper;
import com.pf.mapper.FileMapper;
import com.pf.mapper.entity.FileEntity;
import com.pf.utils.ResultRespUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/7/1 20:57
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private CustomFileHelper customFileHelper;
    @Autowired
    private FileMapper fileMapper;

    @PostMapping("/upload")
    public ResultResp<UploadFileResp> upload(@RequestParam("file") MultipartFile file) throws Exception {
        UploadFileResp targetFile = customFileHelper.upload(file);
        return ResultRespUtils.success(targetFile);
    }

    @GetMapping("/download/{fileId}")
    public void download(@PathVariable("fileId") String fileId, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            FileEntity fileEntity = fileMapper.selectOne(new LambdaQueryWrapper<FileEntity>()
                    .eq(FileEntity::getFileId, fileId)
            );
            String fileName = fileEntity.getFileName();
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
            File file = customFileHelper.getFile(fileId, fileSuffix);

            byte[] bytes = FileUtils.readFileToByteArray(file);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", bytes.length + "");
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception e) {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


}
